import * as readline from 'readline';
import * as fs from 'fs/promises';
import * as path from 'path';
import { {{camelCase name}}Agent } from '@/agents';

const presetQueries = {
  '1': "What are the latest developments in quantum computing and their potential applications?",
  '2': "How has climate change affected Arctic ice coverage over the past decade?",
  '3': "What are the key differences between various machine learning frameworks?",
  '4': "What are the economic impacts of remote work on urban centers?",
  '5': "How do different countries approach renewable energy policy?",
  '6': "What are the current trends in artificial intelligence safety research?"
};

function showMenu() {
  console.log('\n🔬 {{name}} Deep Research Agent CLI');
  console.log('='.repeat(50));
  console.log('\nPreset Research Queries:');
  
  Object.entries(presetQueries).forEach(([key, query]) => {
    console.log(`  ${key}. ${query}`);
  });
  
  console.log('\n  c. Custom research query');
  console.log('  h. Show this menu');
  console.log('  q. Quit');
  console.log('\n' + '='.repeat(50));
}

async function saveResultToFile(query: string, result: any) {
  try {
    // Create results directory if it doesn't exist
    const resultsDir = path.join(process.cwd(), 'results');
    await fs.mkdir(resultsDir, { recursive: true });
    
    // Create filename from query (sanitized)
    const sanitizedQuery = query
      .replace(/[^a-zA-Z0-9\s]/g, '')
      .replace(/\s+/g, '-')
      .toLowerCase()
      .substring(0, 50);
    
    const timestamp = new Date().toISOString().split('T')[0];
    const filename = `${timestamp}-${sanitizedQuery}.md`;
    const filepath = path.join(resultsDir, filename);
    
    // Format the result as markdown
    const markdown = `# Deep Research Results

**Query:** ${query}

**Date:** ${new Date().toLocaleString()}

**Completion Status:** ${result.result.isComplete ? '✅ Complete' : '⚠️ Incomplete'}

**Research Iterations:** ${result.result.iterations}

## Summary

${result.result.summary}

## Research Analysis

**Completion Reason:** ${result.result.reason}

${result.result.factsJudgment ? `
**Facts Assessment:** ${result.result.factsJudgment.hasEnoughFacts ? 'Sufficient' : 'Insufficient'}

**Assessment Reasoning:** ${result.result.factsJudgment.reason}

${result.result.factsJudgment.missingAspects.length > 0 ? `
**Missing Aspects Identified:**
${result.result.factsJudgment.missingAspects.map((aspect: string) => `- ${aspect}`).join('\n')}
` : ''}
` : ''}

${result.result.searchPlans ? `
## Search Strategy

${result.result.searchPlans}
` : ''}

## Sources

${result.result.sources.map((source: any, index: number) => 
  `${index + 1}. [${source.title || 'Untitled'}](${source.url})`
).join('\n')}

## Extracted Facts

${result.result.facts ? result.result.facts.map((fact: any, index: number) => 
  `${index + 1}. ${fact.text} (Source: ${fact.sourceIndex + 1})`
).join('\n') : 'No facts extracted'}

---

*Generated by {{name}} Deep Research Agent*
`;
    
    await fs.writeFile(filepath, markdown, 'utf8');
    console.log(`\n💾 Results saved to: ${filepath}`);
    
  } catch (error) {
    console.error(`❌ Failed to save results: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
}

async function runAgent(query: string, rl: readline.Interface) {
  const startTime = Date.now();
  console.log(`\n🔬 Starting deep research on: "${query}"`);
  console.log('⏳ This may take several minutes as we perform comprehensive research...\n');

  try {
    const result = await {{camelCase name}}Agent.run({
      message: query
    });
    const duration = Math.round((Date.now() - startTime) / 1000);

    console.log(`✅ Research completed in ${duration}s\n`);
    console.log('📄 Research Summary:');
    console.log('='.repeat(80));
    
    // Print the main summary
    if (result.result.summary) {
      console.log(result.result.summary);
    }
    
    console.log('\n📊 Research Statistics:');
    console.log(`• Research Iterations: ${result.result.iterations}`);
    console.log(`• Sources Analyzed: ${result.result.sources.length}`);
    console.log(`• Facts Extracted: ${result.result.facts?.length || 0}`);
    console.log(`• Completion Status: ${result.result.isComplete ? '✅ Complete' : '⚠️ Incomplete'}`);
    console.log(`• Completion Reason: ${result.result.reason}`);
    
    if (result.result.factsJudgment && !result.result.factsJudgment.hasEnoughFacts) {
      console.log('\n⚠️ Research Gaps Identified:');
      result.result.factsJudgment.missingAspects.forEach((aspect: string) => {
        console.log(`  • ${aspect}`);
      });
    }
    
    console.log('='.repeat(80));
    
    // Ask if user wants to save results using the existing readline interface
    const saveChoice = await prompt(rl, '\n💾 Save detailed results to file? (y/N): ');
    if (saveChoice.toLowerCase() === 'y' || saveChoice.toLowerCase() === 'yes') {
      await saveResultToFile(query, result);
    }
    
  } catch (error) {
    const duration = Math.round((Date.now() - startTime) / 1000);
    console.log(`❌ Research failed after ${duration}s`);
    console.log(`Error: ${error instanceof Error ? error.message : 'Unknown error'}\n`);
  }
}

function prompt(rl: readline.Interface, message: string): Promise<string> {
  return new Promise((resolve) => {
    rl.question(message, (answer) => resolve(answer.trim()));
  });
}

async function main() {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  console.log('\n🚀 Welcome to the {{name}} Deep Research Agent CLI!');
  console.log('This tool performs comprehensive multi-source research on complex topics.');
  console.log('Research includes web searching, fact extraction, analysis, and synthesis.\n');

  showMenu();

  while (true) {
    const choice = await prompt(rl, '\n🔍 Select a research option (1-6, c, h, q): ');

    switch (choice.toLowerCase()) {
      case 'q':
        console.log('\n👋 Goodbye!');
        rl.close();
        process.exit(0);
      
      case 'h':
        showMenu();
        break;
      
      case 'c':
        const customQuery = await prompt(rl, '\n💭 Enter your research question: ');
        if (customQuery) {
          await runAgent(customQuery, rl);
        } else {
          console.log('❌ No research question provided.');
        }
        break;
      
      default:
        if (presetQueries[choice as keyof typeof presetQueries]) {
          await runAgent(presetQueries[choice as keyof typeof presetQueries], rl);
        } else {
          console.log('❌ Invalid option. Please try again.');
        }
    }
  }
}

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.log('\n\n👋 Goodbye!');
  process.exit(0);
});

// Run the CLI
if (require.main === module) {
  main().catch(console.error);
}